package com.csea.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csea.app.model.vo.repository.RepositoryCreateReqVO;
import com.csea.app.model.vo.repository.RepositoryRspVO;
import com.csea.app.model.vo.repository.RepositoryUpdateReqVO;
import com.csea.app.service.UserRepositoryService;
import com.csea.common.domain.dos.UserIdiomDo;
import com.csea.common.domain.dos.UserRepositoryDo;
import com.csea.common.domain.mapper.UserIdiomMapper;
import com.csea.common.domain.mapper.UserRepositoryMapper;
import com.csea.common.enums.ResponseCodeEnum;
import com.csea.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserRepositoryServiceImpl  extends ServiceImpl<UserRepositoryMapper,UserRepositoryDo> implements UserRepositoryService  {

    @Autowired
    private UserRepositoryMapper repositoryMapper;
    @Autowired
    private UserIdiomMapper userIdiomMapper;

    /**
     * 创建仓库
     *
     * @param reqVO 创建请求
     * @return 创建结果
     */
    @Override
    @Transactional
    public Response<RepositoryRspVO> createRepository(RepositoryCreateReqVO reqVO) {
        Integer userId = reqVO.getUserId();
        if (userId == null || userId <= 0) {
            userId = StpUtil.getLoginIdAsInt();
        }
        String repositoryName = reqVO.getRepositoryName();
        // 根据名字和用户Id检查仓库名称是否已存在
        UserRepositoryDo userRepositoryDo = repositoryMapper.selectByUserIdAndRepositoryName(userId, repositoryName);
        if (userRepositoryDo != null) {
            return Response.fail(ResponseCodeEnum.REPOSITORY_NAME_EXIST_ERROR);
        }
        UserRepositoryDo repository = new UserRepositoryDo();
        BeanUtils.copyProperties(reqVO, repository);
        repository.setUserId(userId);
        repository.setCreateTime(new Date());
        repository.setUpdateTime(new Date());
        repositoryMapper.insert(repository);
        return Response.success(convertToRspVO(repository));
    }

    /**
     * 删除仓库
     *
     * @param repositoryId 仓库ID
     * @return 删除结果
     */
    @Override
    @Transactional
    public Response<String> deleteRepository(Integer repositoryId) {
        UserRepositoryDo userRepositoryDo = repositoryMapper.selectById(repositoryId);
        if (userRepositoryDo == null) {
            return Response.fail(ResponseCodeEnum.REPOSITORY_NOT_FOUND_ERROR);
        }

        int count = repositoryMapper.deleteById(repositoryId);
        if (count == 0) {
            return Response.fail(ResponseCodeEnum.REPOSITORY_NOT_FOUND_ERROR);
        }
        return Response.success("仓库删除成功");
    }

    /**
     * 更新仓库信息
     *
     * @param reqVO 更新请求
     * @return 更新结果
     */
    @Override
    @Transactional
    public Response<RepositoryRspVO> updateRepository(RepositoryUpdateReqVO reqVO) {
        UserRepositoryDo existingRepository = repositoryMapper.selectById(reqVO.getRepositoryId());
        if (existingRepository == null) {
            return Response.fail(ResponseCodeEnum.REPOSITORY_NOT_FOUND_ERROR);
        }
        UserRepositoryDo repository = new UserRepositoryDo();
        BeanUtils.copyProperties(reqVO, repository);
        repository.setUpdateTime(new Date());
        repositoryMapper.updateById(repository);
        return Response.success(convertToRspVO(repositoryMapper.selectById(reqVO.getRepositoryId())));
    }

    /**
     * 获取用户仓库列表
     *
     * @param userId 用户ID
     * @return 仓库列表
     */
    @Override
    public Response<List<RepositoryRspVO>> listUserRepositories(Integer userId) {
        LambdaQueryWrapper<UserRepositoryDo> query = Wrappers.lambdaQuery();
        query.eq(UserRepositoryDo::getUserId, userId)
             .orderByDesc(UserRepositoryDo::getUpdateTime);
        List<UserRepositoryDo> repositories = repositoryMapper.selectList(query);
        
        List<RepositoryRspVO> result = repositories.stream()
                .map(this::convertToRspVO)
                .collect(Collectors.toList());
        return Response.success(result);
    }

    private RepositoryRspVO convertToRspVO(UserRepositoryDo repository) {
        RepositoryRspVO vo = new RepositoryRspVO();

        // 新增统计逻辑
        List<UserIdiomDo> idioms = userIdiomMapper.selectList(
                new LambdaQueryWrapper<UserIdiomDo>()
                        .eq(UserIdiomDo::getRepositoryId, repository.getRepositoryId())
        );

        vo.setTotalWordCount(idioms.size());
        vo.setNewWordCount((int) idioms.stream().filter(i -> i.getCardStatus() == 0).count());
        vo.setReviewWordCount((int) idioms.stream().filter(i -> i.getCardStatus() == 2).count());

        BeanUtils.copyProperties(repository, vo);
        return vo;
    }
}